<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="auto">
          <el-form-item label="方案名称" prop="name">
            <el-input v-model="form.name" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="派送方式" prop="deliveryType">
            <el-select
              v-model="form.deliveryType"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in dict.deliveryType"
                :key="item.id"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="form.deliveryType===0" label="截单时间">
            <el-select v-model="form.stopTime" placeholder="请选择" clearable>
              <el-option
                v-for="item in timeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.deliveryType===0 && form.stopTime!==''" label="截单时间之前延迟配送天数">
            <el-input-number v-model="form.beforeDelayDeliveryDays" :min="0" />
            <template slot="append">天</template>
          </el-form-item>
          <el-form-item v-if="form.deliveryType===0 && form.stopTime!==''" label="截单时间之后延迟配送天数">
            <el-input-number v-model="form.afterDelayDeliveryDays" :min="0" />
            <template slot="append">天</template>
          </el-form-item>
          <el-form-item v-show="form.deliveryType===0" label="订单最早可配送时间间隔">
            <el-input-number v-model="form.deliveryTimeInterval" :min="0">
              <template slot="append">时</template>
            </el-input-number>
          </el-form-item>
          <el-form-item :label="form.deliveryType===0?'订单最晚可配送天数':'订单最晚可自提天数'">
            <el-input-number v-model="form.latestDeliveryDays" :min="0" placeholder="从当前时间延续设定天数">
              <i slot="suffix" style="font-style:normal;margin-right: 10px;">天</i>
            </el-input-number>
          </el-form-item>

          <el-form-item v-if="timeSlotsSet.deliveryType===0 && form.stopTime === ''" label="開始時間">
            <el-time-select
              v-model="deliverStartTime"
              placeholder="開始時間"
              :picker-options="{
                start: '09:00',
                step: '00:30',
                end: '23:00'
              }"
            />
          </el-form-item>
          <el-form-item v-if="timeSlotsSet.deliveryType===0 && form.stopTime === '' " label="結束時間">
            <el-time-select
              v-model="deliverEndTime"
              placeholder="結束時間"
              :picker-options="{
                start: '09:00',
                step: '00:30',
                end: '23:00'
              }"
            />
          </el-form-item>
          <el-form-item v-if="timeSlotsSet.deliveryType===1 && (form.stopTime === '' || form.stopTime === null) " label="開始時間">
            <el-time-select
              v-model="startTime"
              placeholder="開始時間"
              :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '23:59'
              }"
            />
          </el-form-item>
          <el-form-item v-if="timeSlotsSet.deliveryType===1 && (form.stopTime === '' || form.stopTime === null) " label="結束時間">
            <el-time-select
              v-model="endTime"
              placeholder="結束時間"
              :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '23:59',
              }"
            />
          </el-form-item>
          <el-form-item v-if="form.stopTime === '' || form.stopTime === null" label="配额">
            <el-input-number v-model="quota" :min="0" />
            <el-button v-if="timeSlotsSet.deliveryType===0" class="littleMarginLeft" type="success" plain @click="deliverTimeList">增加時間段</el-button>
          </el-form-item>
          <el-form-item v-if="form.stopTime === '' || form.stopTime === null ">
            <el-tag
              v-for="(item,index) in deliverTimesList"
              :key="index"
              closable
              style="margin-right: 10px; clear：left(right，both) ;font-size: 17px"
              @close="tagClose(index)"
            >{{ item }}
            </el-tag>
          </el-form-item>

          <el-form-item label="是否启用">
            <el-switch v-model="form.enable" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-right: 40%">
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">保存方案</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        row-key="id"
        :data="crud.data"
        style="width: 100%;"
        stripe
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column prop="name" label="派送配置名稱"       />
        <el-table-column prop="deliveryType" label="派送方式"      >
          <template slot-scope="scope">
            {{ dict.label.deliveryType[scope.row.deliveryType] }}
          </template>
        </el-table-column>
        <el-table-column prop="afterDelayDeliveryDays" label="截单后延迟配送天数"       />
        <el-table-column prop="beforeDelayDeliveryDays" label="截单前延迟配送天数"       />
        <el-table-column prop="deliveryTimeInterval" label="最早可配送时间间隔"       />
        <el-table-column prop="latestDeliveryDays" label="最晚可配送天数"       />
        <el-table-column prop="stopTime" label="截单时间"       />
        <el-table-column prop="enable" label="是否可用"      >
          <template slot-scope="scope">
            <mall-switch
              :row="scope.row"
              :dict-data="dict.label.sysStatus"
              :row-data="scope.row.enable"
              row-filed="enable"
              to-true-character="启用"
              to-false-character="禁用"
              title="派送配置"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkPer(['admin','deliverSet:edit','deliverSet:del'])"
          label="操作"

        >
          <template slot-scope="scope">
            <div>
              <udOperation
                :data="scope.row"
                :permission="permission"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDeliverSet from '@/api/sms/deliverSet'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import mallSwitch from '@/components/mallSwitch'

const defaultForm = {
  id: null,
  afterDelayDeliveryDays: 0,
  beforeDelayDeliveryDays: 0,
  deliveryTimeInterval: 0,
  latestDeliveryDays: null,
  name: null,
  stopTime: '',
  enable: false,
  deliveryType: 0,
  timeSlots: []
}
export default {
  name: 'DeliverSet',
  components: { pagination, crudOperation, udOperation, mallSwitch },
  dicts: ['deliveryType', 'sysStatus'],
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '派送方案', url: 'deliverSet/page', sort: 'id:desc', crudMethod: { ...crudDeliverSet },
      optShow: {
        add: true,
        edit: false,
        del: false,
        download: false,
        reset: true
      }
    })
  },
  data() {
    return {
      hasStopTime: true,
      timeSlots: [],
      timeSlotsSet: [],
      startTime: '',
      endTime: '',
      deliverEndTime: '',
      deliverStartTime: '',
      quota: 0,
      tagValue: [],
      options: [],
      deliveryTypeOptions: [{ label: '商家配送', value: '0' }, { label: '用户自提', value: '1' }],
      timeOption: [],
      deliverTimesList: [],
      permission: {
        add: ['admin', 'deliverSet:add'],
        edit: ['admin', 'deliverSet:edit'],
        del: ['admin', 'deliverSet:del']
      },
      closeConfiguration: true,
      rules: {
        name: [
          { required: true, message: '配置名称不能为空', trigger: 'blur' }
        ],
        deliveryType: [
          { required: true, message: '配送方式不能为空', trigger: 'blur' }
        ]

      }
    }
  },
  created() {
    this.tagValue
    for (let i = 0; i < 24; i++) {
      var onHour1 = (i + ':00')
      var halfHour1 = (i + ':30')
      this.timeOption.push({ label: onHour1, value: onHour1 })
      this.timeOption.push({ label: halfHour1, value: halfHour1 })
    }
    for (let i = 10; i < 22; i += 2) {
      const t1 = (i + ':00')
      const t2 = ((i + 2) + ':00')
      var tt = t1 + '-' + t2
      this.options.push({ label: tt, value: tt })
    }
  },
  methods: {
    [CRUD.HOOK.beforeToEdit](crud, data) {
      this.setTimeSlots(data)
      return true
    },
    [CRUD.HOOK.beforeSubmit]() {
      if (this.timeSlotsSet.deliveryType === 1) {
        this.timeSlotsSet.timeSlots = [{ quota: this.quota, timeSlot: this.startTime + '-' + this.endTime }]
      } else {
        this.timeSlotsSet.timeSlots = this.timeSlots
      }
    },
    [CRUD.HOOK.afterSubmit]() {
      this.deliverTimesList = []
      this.timeSlots = []
    },
    [CRUD.HOOK.beforeToAdd]() {
      this.deliverTimesList = []
      this.timeSlots = []
    },
    deliverTimeList() {
      if (this.deliverEndTime === null || this.deliverEndTime === '' || this.deliverStartTime === null || this.deliverStartTime === '') {
        this.$message({
          message: '配送時間段不能为空',
          type: 'warning',
          duration: 1000
        })
        return
      }
      const slots = []
      for (const data of this.timeSlots) {
        slots.push(data.timeSlot)
      }
      if (slots.indexOf(this.deliverStartTime + '-' + this.deliverEndTime) !== -1) {
        this.$message({
          message: '配送時間段不能重复',
          type: 'warning',
          duration: 1000
        })
        return
      }
      this.deliverTimesList.push(this.deliverStartTime + '-' + this.deliverEndTime + '  (配額:' + this.quota + ')')
      this.timeSlots.push({ quota: this.quota, timeSlot: this.deliverStartTime + '-' + this.deliverEndTime })
      this.deliverStartTime = ''
      this.deliverEndTime = ''
      this.quota = 0
    },
    tagClose(index) {
      this.deliverTimesList.splice(index, 1)
      this.timeSlots.splice(index, 1)
    },

    setTimeSlots(row) {
      this.timeSlotsSet = []
      this.timeSlots = []
      this.deliverTimesList = []
      this.timeSlotsSet = row
      if (this.timeSlotsSet.deliveryType === 1) {
        const strings = this.timeSlotsSet.timeSlots[0].timeSlot.toString().split('-')
        this.startTime = strings[0]
        this.endTime = strings[1]
      }
      if (this.timeSlotsSet.deliveryType === 0) {
        const timeSlots = this.timeSlotsSet.timeSlots
        for (let i = 0; i < timeSlots.length; i++) {
          this.deliverTimesList.push(timeSlots[i].timeSlot + '  (配額:' + timeSlots[i].quota + ')')
          this.timeSlots.push({ quota: timeSlots[i].quota, timeSlot: timeSlots[i].timeSlot })
        }
      }
    },
    handleClose() {
      this.$confirm('確認關閉？')
        .then(_ => {
          this.timeSlotsSet = []
          this.timeSlots = []
          this.deliverTimesList = []
        }).catch(_ => {})
    }
  }
}
</script>

<style scoped>

</style>
